package com.itheima;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 模拟从数据库查找用户名和密码
 */
@Component
public class SecurityService implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    Map<String, User> map = new HashMap<>();

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //初始化map 用户数据库使用
        initData();

        //自定义权限
        List<GrantedAuthority> list1 = new ArrayList<>();
        SimpleGrantedAuthority role_add = new SimpleGrantedAuthority("ROLE_ADD");//授予角色
        list1.add(role_add);

        List<GrantedAuthority> list2 = new ArrayList<>();
        SimpleGrantedAuthority role_delete = new SimpleGrantedAuthority("ROLE_DELETE");//授予角色
        SimpleGrantedAuthority query = new SimpleGrantedAuthority("QUERY");//授予权限
        list2.add(role_delete);
        list2.add(query);

        //获取map中对应的key
        Set<String> keys = map.keySet();
        //获取从表单得到的用户名和密码，赋予他们不同的权限或角色
        for (String key : keys) {
            if (username.equals(map.get(key).getUsername()))
                if ("zhangsan".equals(username)) {
                    //对用户名为zhangsan的用户进行授权
                    return new org.springframework.security.core.userdetails.User
                            (username, map.get(key).getPassword(), list1);

                }
            if ("lisi".equals(map.get(key).getPassword())) {
                //授予lisi用户权限和角色
                return new org.springframework.security.core.userdetails.User
                        (username, map.get(key).getPassword(), list2);
            }
        }
        return null;
    }



    private void initData() {
        User user1=new User();
        user1.setUsername("zhangsan");
        String password1 = bCryptPasswordEncoder.encode("123");
        user1.setPassword(password1);

        User user2=new User();
        user1.setUsername("lisi");
        String password2 = bCryptPasswordEncoder.encode("123");
        user1.setPassword(password2);

        map.put("zhangsan",user1);
        map.put("lisi",user2);
    }
}
